﻿using System.IO;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;
using iLib.Web.UI;

namespace Cms.Application
{
    public class DashboardGadgetHandler
    {
        public static void SyncGadgets(ISystemRepository systemRepository)
        {
            // Delete all DB gadgets that don't have a ascx
            foreach (DashboardGadget gadget in systemRepository.GetDashboardGadgets())
            {
                if (gadget.CustomGadget) // Custom gadgets are handled elsewhere
                    continue;
                bool found = false;
                foreach (string filepath in Directory.GetFiles(Url.PhysicalPath + "Admin\\DashboardGadgets"))
                {
                    if (gadget.Filename.ToLower() == Path.GetFileName(filepath).ToLower())
                    {
                        found = true;
                        break;
                    }
                }
                if (!found)
                    systemRepository.DeleteDashboardGadget(gadget.ID);
            }
            // Add gadgets that do not yet exist in the DB
            foreach (string filepath in Directory.GetFiles(Url.PhysicalPath + "Admin\\DashboardGadgets"))
            {
                bool found = false;
                foreach (DashboardGadget gadget in systemRepository.GetDashboardGadgets())
                {
                    if (gadget.Filename.ToLower() == Path.GetFileName(filepath).ToLower())
                    {
                        found = true;
                        break;
                    }
                }
                if (!found) // Add new gadget
                {
                    var gadget = new DashboardGadget
                                     {
                                         Filename = Path.GetFileName(filepath),
                                         Activated = true,
                                         CustomGadget = false
                                     };
                    systemRepository.SaveDashboardGadget(gadget);
                }
            }
        }
    }
}